﻿using System.IO;
using System.IO.Compression;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using TradeDataAPI.Core.CacheManager;
using TradeDataAPI.Core.Extensions.AutofacManager;
using TradeDataAPI.Core.Utilities;

namespace TradeDataAPI.Core.Common
{
    public class HttpHelper
    {

        public static Microsoft.AspNetCore.Http.HttpContext Context
        {
            get
            {
                return HttpContext.Current;
            }
        }

        public ICacheService CacheContext
        {
            get
            {
                return AutofacContainerModule.GetService<ICacheService>();
            }
        }

        /// <summary>
        /// 获取当前服务的运行前缀信息
        /// </summary>
        /// <returns></returns>
        public static string Getaddress()
        {

            //调用本服务的接口BatchAddition
            var scheme = Context.Request.Scheme; // 获取请求前缀（http 或 https）
            var host = Context.Request.Host.Host;
            var port = Context.Request.Host.Port;
            return $"{scheme}://{host}:{port}";
        }


        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static byte[] CompressString(string str)
        {
            var bytes = Encoding.UTF8.GetBytes(str);
            using (var msi = new MemoryStream(bytes))
            using (var mso = new MemoryStream())
            {
                using (var gs = new GZipStream(mso, CompressionMode.Compress))
                {
                    msi.CopyTo(gs);
                }
                return mso.ToArray();
            }
        }


        /// <summary>
        /// post请求接口
        /// </summary>
        /// <param name="url"></param>
        /// <param name="compressedContent"></param>
        /// <returns></returns>
        public static async Task<string> PostCompressedJsonAsync(string url, byte[] compressedContent)
        {
            using (var client = new HttpClient())
            {
                var content = new ByteArrayContent(compressedContent);
                content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("application/json");
                content.Headers.ContentEncoding.Add("gzip");

                var response = await client.PostAsync(url, content);

                if (response.IsSuccessStatusCode)
                {
                    return await response.Content.ReadAsStringAsync();
                }
                else
                {
                    return $"Error: {response.StatusCode}";
                }
            }
        }





    }
}
